/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package filecityclient;

import java.awt.BorderLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Point;
import java.awt.event.*;
import java.io.*;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import manager.FileManagerRemote;
import manager.LogManagerRemote;
import manager.UserManagerRemote;
import remoteEntity.*;

/**
 *
 * @author sara
 */
public class GUI extends JFrame {

    @EJB
    private static LogManagerRemote logManager;
    @EJB
    private static UserManagerRemote userManager;
    @EJB
    private static FileManagerRemote fileManager;
    JTextArea textArea = new JTextArea();
    JScrollPane scrollPane = new JScrollPane(textArea);
    JPanel uploadPanel = new JPanel();
    JPanel buttonPanel = new JPanel();
    JPanel topPanel = new JPanel();
    JPanel rightPanel = new JPanel();
    JPanel leftPanel = new JPanel();
    JPanel bottomPanel = new JPanel();
    ImageIcon icon = new ImageIcon("filecity.png");
    JLabel label = new JLabel();
    JButton loginButton = new JButton("Login");
    JButton browseButton = new JButton("Browse");
    JButton uploadButton = new JButton("Upload");
    JButton profileButton = new JButton("My Profile");
    JButton categoriesButton = new JButton("Categories");
    JButton logButton = new JButton("Admin: Log");
    JButton registerButton = new JButton("Register");
    JPanel panel = new JPanel(new BorderLayout());
    JPanel newButtonPanel = new JPanel();
    DefaultTableModel model = new DefaultTableModel();
    JTable table = new JTable(model);
    JScrollPane scrollPaneTable = new JScrollPane(table);
    DefaultTableModel modelCategory = new DefaultTableModel();
    JTable tableCategory = new JTable(modelCategory);
    JScrollPane scrollPaneTableCategory = new JScrollPane(tableCategory);
    File uploadfile;
    JButton addFile = new JButton("Choose file");
    JButton submitFile = new JButton("Submit");
    JButton downloadFile = new JButton("Download file");
    JButton promoteButton = new JButton("Promote");
    JButton demoteButton = new JButton("Demote");
    JLabel labelFilename = new JLabel("Filename: ");
    JTextField filename = new JTextField(20);
    JLabel labelFiledescription = new JLabel("Description: ");
    JTextField filedescription = new JTextField(20);
    JLabel labelCategory = new JLabel("Category: ");
    JTextField category = new JTextField();
    JTextField selectedFile = new JTextField(20);
    List<Category> listCategories;
    int chosenCategory = 1; //Default
    String[] cat;
    JComboBox categoryList;
    final JFileChooser fc = new JFileChooser();
    int fileID;
    int userID;
    List<Filedescription> listC;
    JPanel prodemPanel = new JPanel();
    JComboBox userListCombo = new JComboBox();
    JPanel downloadPanel = new JPanel();
    JPanel centerPanel = new JPanel(new BorderLayout());

    GUI() {

        listCategories = fileManager.getAllCategories();
        listC = fileManager.findAllFileDescriptions();
        cat = new String[listCategories.size()];
        int i = 0;
        for (Category c : listCategories) {
            cat[i] = c.getName();
            i++;
        }
        categoryList = new JComboBox(cat);

        uploadPanel.setLayout(new GridBagLayout());
        GridBagConstraints c = new GridBagConstraints();

        c.gridx = 0;
        c.gridy = 0;
        uploadPanel.add(labelFilename, c);
        c.gridx = 1;
        c.gridy = 0;
        uploadPanel.add(filename, c);
        c.gridx = 0;
        c.gridy = 1;
        uploadPanel.add(labelFiledescription, c);
        c.gridx = 1;
        c.gridy = 1;
        uploadPanel.add(filedescription, c);
        c.gridwidth = 2;
        c.gridx = 1;
        c.gridy = 2;
        uploadPanel.add(categoryList, c);
        c.gridwidth = 2;
        c.gridx = 1;
        c.gridy = 3;
        selectedFile.setVisible(false);
        uploadPanel.add(selectedFile, c);
        c.gridwidth = 2;
        c.gridx = 1;
        c.gridy = 4;
        uploadPanel.add(addFile, c);
        c.gridwidth = 2;
        c.gridx = 1;
        c.gridy = 5;
        uploadPanel.add(submitFile, c);

        promoteButton.addActionListener(new PromoteAction());
        demoteButton.addActionListener(new DemoteAction());
        logButton.addActionListener(new LogAction());
        loginButton.addActionListener(new LoginAction());
        uploadButton.addActionListener(new UploadAction());
        downloadFile.addActionListener(new DownloadAction());
        categoriesButton.addActionListener(new CategoriesAction());
        profileButton.addActionListener(new ProfileAction());
        browseButton.addActionListener(new BrowseAction());
        registerButton.addActionListener(new RegisterAction());
        addFile.addActionListener(new AddFileAction());
        submitFile.addActionListener(new SubmitFileAction());
        label.setIcon(icon);
        topPanel.add(label);

        centerPanel.setBorder(BorderFactory.createLoweredBevelBorder());

        newButtonPanel.add(loginButton);
        newButtonPanel.add(registerButton);
        newButtonPanel.add(browseButton);
        newButtonPanel.add(categoriesButton);

        model.addColumn("Name");
        model.addColumn("Description");
        model.addColumn("Category");
        model.addColumn("User");

        modelCategory.addColumn("Category");
        modelCategory.addColumn("Description");

        centerPanel.add(newButtonPanel, BorderLayout.NORTH);

        JPanel contentPane = new JPanel(new BorderLayout());

        contentPane.add(topPanel, BorderLayout.NORTH);
        contentPane.add(centerPanel, BorderLayout.CENTER);
        contentPane.add(rightPanel, BorderLayout.EAST);
        contentPane.add(leftPanel, BorderLayout.WEST);
        contentPane.add(bottomPanel, BorderLayout.PAGE_END);
        centerPanel.add(panel, BorderLayout.CENTER);

        setContentPane(contentPane);

        setTitle("Filecity");
        setVisible(true);
        setDefaultCloseOperation(EXIT_ON_CLOSE);

        setSize(930, 800);
    }

    public byte[] readFile(File file) throws IOException {

        byte[] buffer;
        InputStream ios = new FileInputStream(file);
        ByteArrayOutputStream ous = new ByteArrayOutputStream();

        try {
            long filesize = file.length();
            double fileinmb = filesize/1024;
            
            if (file != null && fileinmb < 1024) {
                buffer = new byte[4096];
                int read = 0;
                while ((read = ios.read(buffer)) != -1) {
                    ous.write(buffer, 0, read);
                }
            }
            else {
                return null;
            }
        } finally {
            if (ous != null) {
                ous.close();
            }
            if (ios != null) {
                ios.close();

            }
            return ous.toByteArray();
        }
    }

    class PromoteAction implements ActionListener {

        @Override
        public void actionPerformed(ActionEvent e) {
            userManager.promote(userID);
            logManager.logInfo("profile", "User " + userManager.getUser().getUsername()
                    + " (id " + userManager.getUser().getId() + ") promoted user id " + userID + ".");
        }
    }

    class DemoteAction implements ActionListener {

        @Override
        public void actionPerformed(ActionEvent e) {
            userManager.demote(userID);
            logManager.logInfo("profile", "User " + userManager.getUser().getUsername()
                    + " (id " + userManager.getUser().getId() + ") demoted user id " + userID + ".");
        }
    }

    class DownloadAction implements ActionListener {

        @Override
        public void actionPerformed(ActionEvent e) {

            panel.removeAll();
            panel.updateUI();

            try {
                byte[] data = fileManager.getFileBlob(fileID);
                ByteArrayOutputStream f = new ByteArrayOutputStream();

                String name = "";
                JFileChooser fileChooser = new JFileChooser();
                fileChooser.setSelectedFile(new File(name));
                int returnVal = fileChooser.showSaveDialog(downloadFile);
                File fi = null;
                if (JFileChooser.APPROVE_OPTION == returnVal) {
                    try {
                        fi = fileChooser.getSelectedFile();
                    } catch (Exception e4) {
                        //Error...
                    }
                    FileOutputStream fOutputStrm = new FileOutputStream(fi);  // open the output stream.
                    fOutputStrm.write(data);  // write the byte array out to the disk.
                    fOutputStrm.close();  // close the stream.
                }
            } catch (IOException ex) {
                Logger.getLogger(GUI.class.getName()).log(Level.SEVERE, null, ex);
                logManager.logError("download", "User "
                        + userManager.getUser().getUsername()
                        + " tried to download file id " + fileID
                        + " which does not exist");
            }
            logManager.logDownload(userManager.getUser().getId(), fileID);
        }
    }

    class LogAction implements ActionListener {

        @Override
        public void actionPerformed(ActionEvent arg0) {

            panel.removeAll();
            panel.add(scrollPane, BorderLayout.CENTER);
            panel.updateUI();
            textArea.setText("");
            List<Log> logList = logManager.getAllPosts();
            for (Log e : logList) {
                textArea.append("Log entry id=" + e.getId() + " message:" + e.getMessage() + "\n");
            }
        }
    }

    class UploadAction implements ActionListener {

        @Override
        public void actionPerformed(ActionEvent e) {

            panel.removeAll();
            panel.updateUI();

            panel.add(uploadPanel, BorderLayout.CENTER);

            panel.updateUI();
            categoryList.addItemListener(new ItemListener() {

                @Override
                public void itemStateChanged(ItemEvent ie) {
                    chosenCategory = (int) categoryList.getSelectedIndex() + 1;
                }
            });
        }
    }

    class SubmitFileAction implements ActionListener {

        @Override
        public void actionPerformed(ActionEvent e) {
            byte[] fileContent;
            try {
                if (uploadfile != null) {
                    fileContent = readFile(uploadfile);
                    panel.removeAll();
                    panel.add(scrollPane, BorderLayout.CENTER);
                    //TODO: Check file size before adding to assure that it's not to big.
                    if (fileContent != null && fileContent.length > 10) {
                        fileManager.addFile(fileContent, filename.getText(), filedescription.getText(), chosenCategory, userManager.getUser());

                        textArea.setText("File successfully uploaded!");
                        panel.updateUI();
                        selectedFile.setVisible(false);
                        filename.setText("");
                        filedescription.setText("");
                    } else {
                        textArea.setText("File too big!");
                        panel.updateUI();
                    }
                } else {
                    panel.removeAll();
                    panel.add(scrollPane, BorderLayout.CENTER);
                    panel.updateUI();
                    textArea.setText("You need to specify a file! Press the Upload button to try again.\n");
                }

            } catch (IOException ex) {
                Logger.getLogger(GUI.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    class AddFileAction implements ActionListener {

        @Override
        public void actionPerformed(ActionEvent e) {
            panel.removeAll();
            panel.add(uploadPanel, BorderLayout.CENTER);
            panel.updateUI();
            //Create a file chooser
            final JFileChooser fc = new JFileChooser();
            //Handle open button action.
            int returnVal = fc.showOpenDialog(GUI.this);

            if (returnVal == JFileChooser.APPROVE_OPTION) {
                uploadfile = fc.getSelectedFile();
                selectedFile.setText(fc.getSelectedFile().toString());
                selectedFile.setVisible(true);
                panel.updateUI();

            } else {
                panel.removeAll();
                panel.add(scrollPane, BorderLayout.CENTER);
                panel.updateUI();
                textArea.setText("Upload command cancelled by user.\n");
            }
        }
    }

    class ProfileAction implements ActionListener {

        @Override
        public void actionPerformed(ActionEvent e) {

            panel.removeAll();
            panel.add(scrollPane, BorderLayout.CENTER);
            panel.updateUI();

            textArea.setText("");
            textArea.append("Profile \n");
            textArea.append("\n");
            textArea.append("Firstname: " + userManager.getUser().getFirstname() + "\n");
            textArea.append("Lastname: " + userManager.getUser().getLastname() + "\n");
            textArea.append("Username: " + userManager.getUser().getUsername() + "\n");
            textArea.append("Email: " + userManager.getUser().getEmail() + "\n");
            textArea.append("\n");
            textArea.append("Download history\n");
            textArea.append("\n");

            List<Download> list = logManager.getDownladsForUser(userManager.getUser().getId());
            final List<Filedescription> listDesc = fileManager.findAllFileDescriptions();

            for (Download d : list) {
                int fileId = d.getFiledescriptionId();
                for (Filedescription f : listDesc) {
                    int id = f.getId();
                    if (fileId == id) {
                        String filename = f.getName();
                        textArea.append(d.getTimestamp() + "   " + filename + "\n");
                    }
                }
            }
            panel.updateUI();
        }
    }

    class RegisterAction implements ActionListener {

        @Override
        public void actionPerformed(ActionEvent e) {

            panel.removeAll();
            panel.add(scrollPane);
            panel.updateUI();

            JLabel jfirstname = new JLabel("Firstname: ");
            JTextField firstname = new JTextField();
            JLabel jlastname = new JLabel("Lastname: ");
            JTextField lastname = new JTextField();
            JLabel jemail = new JLabel("Email: ");
            JTextField email = new JTextField();
            JLabel jusername = new JLabel("User Name: ");
            JTextField username = new JTextField();
            JLabel jPassword = new JLabel("Password: ");
            JTextField password = new JPasswordField();
            JLabel jconfirmPassword = new JLabel("Confirm password: ");
            JTextField confirmPassword = new JPasswordField();
            Object[] ob = {jfirstname, firstname, jlastname, lastname, jemail, email, jusername, username, jPassword,
                password, jconfirmPassword, confirmPassword};
            int result = JOptionPane.showConfirmDialog(null, ob, "Register", JOptionPane.OK_CANCEL_OPTION);

            String firstnameValue = "";
            String lastnameValue = "";
            String usernameValue = "";
            String emailValue = "";
            String passwordValue = "";
            String confirmPasswordValue = "";

            if (result == JOptionPane.OK_OPTION) {
                firstnameValue = firstname.getText();
                lastnameValue = lastname.getText();
                emailValue = email.getText();
                usernameValue = username.getText();
                passwordValue = password.getText();
                confirmPasswordValue = confirmPassword.getText();
            }
            if (firstnameValue.equals("") || lastnameValue.equals("") || emailValue.equals("") || usernameValue.equals("") || passwordValue.equals("") || confirmPasswordValue.equals("")) {
                textArea.setText("You have to fill in all values! Click the register button to try again!");
            } else {

                if (!passwordValue.equals(confirmPasswordValue)) {
                    textArea.setText("Password and confirm password are not equal. Click the register button to try again!");
                } else {

                    try {
                        userManager.setFields(usernameValue, passwordValue, emailValue, firstnameValue, lastnameValue);
                        userManager.register();
                        textArea.setText("Registration successful!");

                    } catch (Exception ex) {
                        Logger.getLogger(GUI.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            }
        }
    }

    class LoginAction implements ActionListener {

        @Override
        public void actionPerformed(ActionEvent arg0) {

            panel.removeAll();
            textArea.setText("");
            panel.add(scrollPane, BorderLayout.CENTER);
            panel.updateUI();

            JLabel jUserName = new JLabel("User Name");
            JTextField userName = new JTextField();
            JLabel jPassword = new JLabel("Password");
            JTextField password = new JPasswordField();
            Object[] ob = {jUserName, userName, jPassword, password};
            int result = JOptionPane.showConfirmDialog(null, ob, "Login", JOptionPane.OK_CANCEL_OPTION);

            String userNameValue = "";
            String passwordValue = "";
            if (result == JOptionPane.OK_OPTION) {
                userNameValue = userName.getText();
                passwordValue = password.getText();
            }
            if (userNameValue.equals("") || passwordValue.equals("")) {
                textArea.setText("Username/password required!");
            } else {

                attemptLogin(userNameValue, passwordValue);

                try {

                    if (userManager.getUser().getFirstname() == null) {
                        textArea.setText("Wrong username/password! Press Login button to try again");
                        textArea.updateUI();

                    } else {

                        try {
                            textArea.setText("");
                            User us = userManager.getUser();
                            textArea.append("Welcome " + us.getFirstname() + " " + us.getLastname() + "!\n");
                            textArea.append("To browse or upload files, click on the buttons above!");
                            panel.updateUI();

                            if (userManager.getIsAdmin()) {
                                newButtonPanel.add(logButton);
                            }
                            newButtonPanel.remove(registerButton);
                            newButtonPanel.add(uploadButton);
                            newButtonPanel.add(profileButton);
                            newButtonPanel.remove(loginButton);
                            panel.updateUI();

                        } catch (Exception e) {
                            textArea.setText(e.getMessage());
                            textArea.updateUI();
                            panel.updateUI();

                        }
                    }
                } catch (Exception e) {
                    textArea.setText("Something went wrong! Press Login button to try again");
                    textArea.setText(e.getMessage());
                    textArea.updateUI();
                    panel.updateUI();
                }
            }
        }
    }

    private boolean attemptLogin(String username, String password) {
        userManager.setFields(username, password, null, null, null);
        try {
            userManager.login();
        } catch (Exception e) {
        }
        return userManager.getLoggedIn();
    }

    class BrowseAction implements ActionListener {

        @Override
        public void actionPerformed(ActionEvent e) {

            listC = fileManager.findAllFileDescriptions();
            panel.removeAll();
            panel.updateUI();

            if (model.getRowCount() > 0) {
                for (int i = model.getRowCount() - 1; i > -1; i--) {
                    model.removeRow(i);
                }
            }
            panel.add(scrollPaneTable, BorderLayout.CENTER);

            final List<Filedescription> list = fileManager.findAllFileDescriptions();
            for (Filedescription c : list) {
                model.addRow(new Object[]{c.getName(), c.getDescription(), c.getCategory().getName(), c.getUser().getFirstname() + " " + c.getUser().getLastname()});

            }
            table.addMouseListener(new MouseAdapter() {

                @Override
                public void mouseClicked(MouseEvent e) {

                    Point p = e.getPoint();
                    int row = table.rowAtPoint(p);
                    int col = table.columnAtPoint(p);

                    fileID = list.get(row).getId();


                    switch (col) {
                        case 0:

                            if (listC.size() > row) {
                                panel.remove(scrollPaneTable);
                                panel.add(scrollPane, BorderLayout.CENTER);


                                textArea.setText("");
                                textArea.append("Filename: " + list.get(row).getName() + "\n");
                                textArea.append("Description: " + list.get(row).getDescription() + "\n");
                                textArea.append("Date uploaded: " + list.get(row).getDatecreated() + "\n");
                                textArea.append("Uploader: " + list.get(row).getUser().getFirstname() + " " + list.get(row).getUser().getLastname() + "\n");
                                panel.add(downloadPanel, BorderLayout.SOUTH);

                                boolean loggedIn = userManager.getLoggedIn();
                                if (loggedIn == true) {
                                    downloadPanel.add(downloadFile, BorderLayout.SOUTH);
                                } else {
                                    textArea.append("\nLog in to download file!");
                                }
                            }
                            panel.updateUI();
                            break;
                        case 2:
                            final String category = list.get(row).getCategory().getName();

                            if (model.getRowCount() > 0) {
                                for (int i = model.getRowCount() - 1; i > -1; i--) {
                                    model.removeRow(i);
                                }
                            }

                            listC = fileManager.findAllFileDescriptions();

                            for (Filedescription c : list) {
                                if (category.equals(c.getCategory().getName())) {
                                    model.addRow(new Object[]{c.getName(), c.getDescription(), c.getCategory().getName(), c.getUser().getFirstname() + " " + c.getUser().getLastname()});
                                } else {
                                    listC.remove(c);
                                }
                            }

                            table.addMouseListener(new MouseAdapter() {

                                @Override
                                public void mouseClicked(MouseEvent insideTable) {

                                    Point p = insideTable.getPoint();
                                    int r = table.rowAtPoint(p);
                                    int c = table.columnAtPoint(p);

                                    switch (c) {
                                        case 0:

                                            if (listC.size() > r) {

                                                panel.remove(scrollPaneTable);
                                                panel.add(scrollPane, BorderLayout.CENTER);
                                                textArea.setText("");


                                                textArea.append("Filename: " + listC.get(r).getName() + "\n");
                                                textArea.append("Description: " + listC.get(r).getDescription() + "\n");
                                                textArea.append("Date uploaded: " + listC.get(r).getDatecreated() + "\n");
                                                textArea.append("Uploader: " + listC.get(r).getUser().getFirstname() + " " + listC.get(r).getUser().getLastname() + "\n");
                                                panel.add(downloadPanel, BorderLayout.SOUTH);

                                                boolean loggedIn = userManager.getLoggedIn();
                                                if (loggedIn == true) {
                                                    downloadPanel.add(downloadFile, BorderLayout.SOUTH);
                                                } else {
                                                    textArea.append("\nLog in to download file!");
                                                }
                                            }
                                            panel.updateUI();
                                            break;
                                        case 3:

                                            if (listC.size() > r) {
                                                panel.remove(downloadFile);
                                                panel.remove(scrollPaneTable);
                                                panel.add(scrollPane, BorderLayout.CENTER);


                                                textArea.setText("");
                                                textArea.append("First name: " + listC.get(r).getUser().getFirstname() + "\n");
                                                textArea.append("Last name: " + listC.get(r).getUser().getLastname() + "\n");
                                                textArea.append("Username: " + listC.get(r).getUser().getUsername() + "\n");
                                                textArea.append("Email: " + listC.get(r).getUser().getEmail() + "\n");
                                                textArea.append("Role: " + listC.get(r).getUser().getRole().getName() + "\n");
                                                textArea.append("ID: " + listC.get(r).getUser().getId() + "\n");
                                                textArea.append("\n");
                                                textArea.append("Download history\n");
                                                textArea.append("\n");

                                                List<Download> listDown = logManager.getDownladsForUser(listC.get(r).getUser().getId());
                                                final List<Filedescription> listDesc = fileManager.findAllFileDescriptions();


                                                for (Download d : listDown) {
                                                    int fileId = d.getFiledescriptionId();
                                                    for (Filedescription f : listDesc) {
                                                        int id = f.getId();
                                                        if (fileId == id) {
                                                            String filename = f.getName();
                                                            textArea.append(d.getTimestamp() + "   " + filename + "\n");
                                                        }
                                                    }
                                                }

                                                if (userManager.getIsAdmin()) {
                                                    prodemPanel.removeAll();
                                                    panel.add(prodemPanel, BorderLayout.SOUTH);
                                                    if (userManager.getIsAdmin(userID) == true) {
                                                        prodemPanel.add(demoteButton, BorderLayout.SOUTH);
                                                    } else {
                                                        prodemPanel.add(promoteButton, BorderLayout.SOUTH);
                                                    }
                                                }
                                            }
                                            panel.updateUI();
                                            break;
                                        default:
                                            break;
                                    }
                                }
                            });

                            break;
                        case 3:
                            if (listC.size() > row) {

                                panel.remove(downloadFile);
                                panel.remove(scrollPaneTable);
                                panel.add(scrollPane, BorderLayout.CENTER);

                                textArea.setText("");
                                textArea.append("First name: " + list.get(row).getUser().getFirstname() + "\n");
                                textArea.append("Last name: " + list.get(row).getUser().getLastname() + "\n");
                                textArea.append("Username: " + list.get(row).getUser().getUsername() + "\n");
                                textArea.append("Email: " + list.get(row).getUser().getEmail() + "\n");
                                textArea.append("Role: " + list.get(row).getUser().getRole().getName() + "\n");
                                textArea.append("ID: " + list.get(row).getUser().getId() + "\n");
                                textArea.append("\n");
                                textArea.append("Download history\n");
                                textArea.append("\n");

                                userID = list.get(row).getUser().getId();

                                List<Download> listDown = logManager.getDownladsForUser(list.get(row).getUser().getId());
                                final List<Filedescription> listDesc = fileManager.findAllFileDescriptions();

                                for (Download d : listDown) {
                                    int fileId = d.getFiledescriptionId();
                                    for (Filedescription f : listDesc) {
                                        int id = f.getId();
                                        if (fileId == id) {
                                            String filename = f.getName();
                                            textArea.append(d.getTimestamp() + "   " + filename + "\n");
                                        }
                                    }
                                }

                                if (userManager.getIsAdmin()) {
                                    prodemPanel.removeAll();
                                    panel.add(prodemPanel, BorderLayout.SOUTH);
                                    if (userManager.getIsAdmin(userID) == true) {
                                        prodemPanel.add(demoteButton, BorderLayout.SOUTH);
                                    } else {
                                        prodemPanel.add(promoteButton, BorderLayout.SOUTH);
                                    }
                                }
                            }
                            panel.updateUI();
                            break;
                        default:
                            break;
                    }
                }
            });
            panel.updateUI();
        }
    }

    class CategoriesAction implements ActionListener {

        @Override
        public void actionPerformed(ActionEvent e) {
            panel.removeAll();

            panel.updateUI();

            if (modelCategory.getRowCount() > 0) {
                for (int i = modelCategory.getRowCount() - 1; i > -1; i--) {
                    modelCategory.removeRow(i);
                }
            }

            panel.add(scrollPaneTableCategory, BorderLayout.CENTER);

            final List<Category> listCategories = fileManager.getAllCategories();
            for (Category c : listCategories) {
                modelCategory.addRow(new Object[]{c.getName(), c.getDescription()});
            }

            final List<Filedescription> listFiles = fileManager.findAllFileDescriptions();

            tableCategory.addMouseListener(new MouseAdapter() {

                @Override
                public void mouseClicked(MouseEvent e) {

                    Point p = e.getPoint();
                    int row = tableCategory.rowAtPoint(p);
                    String category = listCategories.get(row).getName();

                    panel.remove(scrollPaneTableCategory);
                    panel.updateUI();
                    panel.add(scrollPaneTable);

                    if (model.getRowCount() > 0) {
                        for (int j = model.getRowCount() - 1; j > -1; j--) {
                            model.removeRow(j);
                        }
                    }


                    final List<Filedescription> list = fileManager.findAllFileDescriptions();
                    listC = fileManager.findAllFileDescriptions();

                    for (Filedescription c : list) {
                        if (category.equals(c.getCategory().getName())) {
                            model.addRow(new Object[]{c.getName(), c.getDescription(), c.getCategory().getName(), c.getUser().getFirstname() + " " + c.getUser().getLastname()});
                        } else {
                            listC.remove(c);
                        }
                    }
                }
            });

            table.addMouseListener(new MouseAdapter() {

                @Override
                public void mouseClicked(MouseEvent insideTable) {

                    Point p = insideTable.getPoint();
                    int r = table.rowAtPoint(p);
                    int c = table.columnAtPoint(p);

                    switch (c) {
                        case 0:
                            if (listC.size() > r) {
                                panel.remove(scrollPaneTable);
                                panel.add(scrollPane, BorderLayout.CENTER);
                                textArea.setText("");
                                textArea.append("Filename: " + listC.get(r).getName() + "\n");
                                textArea.append("Description: " + listC.get(r).getDescription() + "\n");
                                textArea.append("Date uploaded: " + listC.get(r).getDatecreated() + "\n");
                                textArea.append("Uploader: " + listC.get(r).getUser().getFirstname() + " " + listC.get(r).getUser().getLastname() + "\n");
                                panel.add(downloadPanel, BorderLayout.SOUTH);

                                boolean loggedIn = userManager.getLoggedIn();
                                if (loggedIn == true) {
                                    downloadPanel.add(downloadFile, BorderLayout.SOUTH);
                                } else {
                                    textArea.append("\nLog in to download file!");
                                }

                                panel.updateUI();
                            }
                            break;
                        case 3:
                            panel.remove(downloadFile);
                            panel.remove(scrollPaneTable);
                            panel.add(scrollPane, BorderLayout.CENTER);

                            if (listC.size() > r) {
                                textArea.setText("");
                                textArea.append("First name: " + listC.get(r).getUser().getFirstname() + "\n");
                                textArea.append("Last name: " + listC.get(r).getUser().getLastname() + "\n");
                                textArea.append("Username: " + listC.get(r).getUser().getUsername() + "\n");
                                textArea.append("Email: " + listC.get(r).getUser().getEmail() + "\n");
                                textArea.append("Role: " + listC.get(r).getUser().getRole().getName() + "\n");
                                textArea.append("ID: " + listC.get(r).getUser().getId() + "\n");
                                textArea.append("\n");
                                textArea.append("Download history\n");
                                textArea.append("\n");

                                List<Download> listDown = logManager.getDownladsForUser(listC.get(r).getUser().getId());
                                final List<Filedescription> listDesc = fileManager.findAllFileDescriptions();


                                for (Download d : listDown) {
                                    int fileId = d.getFiledescriptionId();
                                    for (Filedescription f : listDesc) {
                                        int id = f.getId();
                                        if (fileId == id) {
                                            String filename = f.getName();
                                            textArea.append(d.getTimestamp() + "   " + filename + "\n");
                                        }
                                    }
                                }

                                if (userManager.getIsAdmin()) {
                                    prodemPanel.removeAll();
                                    panel.add(prodemPanel, BorderLayout.SOUTH);
                                    if (userManager.getIsAdmin(userID) == true) {
                                        prodemPanel.add(demoteButton, BorderLayout.SOUTH);
                                    } else {
                                        prodemPanel.add(promoteButton, BorderLayout.SOUTH);
                                    }
                                }
                            }

                            panel.updateUI();
                            break;
                        default:
                            break;
                    }
                }
            });
            panel.updateUI();
        }
    }

    public static void main(String[] args) {
        new GUI();
    }
}